<?php

require "../connect.php";
$filename = $_GET['filename'];


$id = $_GET['id'];

if (is_file($filename) == true) {


    $time = filemtime($filename);
    $query = "INSERT INTO open_files(opened_by,filename,modified_time) VALUES(" . $id . ",'$filename',$time)";
    //var_dump($query);
    $db->query($query);

    $contents = file($filename, FILE_IGNORE_NEW_LINES);

    $query = "SELECT * FROM file_sync 
                        WHERE (file_path='$filename') AND entry_time>$time  
                        ORDER BY entry_time ASC";

    $res = $db->query($query);

    $mod_time = $time;
    foreach ($res as $result) {
        //echo "\nU occured\n";
       // $diff = null;
       // $diff->type = $result['type'];
       // $diff->file = $result['file_path'];
       // $diff->diff = $result['chars'];
        //$diff->pos = $result['pos'];
        if($result['type']=='M'){
            $contents[$result['pos']] = $result['chars']; //modified line
        }
        else if($result['type']=='D'){
            array_splice($contents,$result['pos']); //delete all lines from this position
        }

        if ($result['entry_time'] > $mod_time) {
            $mod_time = $result['entry_time'];
        }

       // $differences[] = $diff;
    }
    $query = "UPDATE `open_files` 
                  SET `modified_time` =" . $mod_time . "  WHERE filename='" . $filename . "' AND opened_by=" . $id;
    $db->query($query);


    echo implode("\n",$contents);
} else {
    echo "invalid";
}

